package com.ww.core.util.http;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;


/**
 * HttpTask 网络任务基础类 输入：请求的HashMap 输出：返回JSONObject
 * 
 */
public class HttpTask extends
		AsyncTask<HashMap<String, String>, Integer, JSONObject> {

	public static int REQUEST_TYPE_POST = 0;
	public static int REQUEST_TYPE_GET = 1;
	private int mRequestType = 0;

	private Context mActivity = null;
	private String uriAPI = null;
	private RequestObject mRequestObject = null;
	private int mRequestID = -1;
	//private int timeout = 30000;
	private IHttpResponse mIHttpResponse = null;
	private ProgressDialog mDialog = null;
	public HttpTask() {
	}

	@Override
	protected JSONObject doInBackground(HashMap<String, String>... params) {
		HashMap<String, String> requestHashMap = params[0];
		JSONObject responseObject = null;
		HttpPost httpPost = null;
		HttpGet httpGet = null;
		if (mRequestType == REQUEST_TYPE_POST) {
			httpPost = new HttpPost(this.uriAPI);// 建立HTTP Post连线
			httpPost.addHeader("user-agent", "android");
		} else {
			httpGet = new HttpGet(this.uriAPI);// 建立HTTPget连线
		}

		// {Post运作传送变数必须用NameValuePair[]阵列储存传参数,
		// 服务端获取的方法为request.getParameter("name")}
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		if (requestHashMap != null) {
			Set<String> set = requestHashMap.keySet();
			for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
				String object = iterator.next();
				formparams.add(new BasicNameValuePair(object,
						(String) requestHashMap.get(object)));
			}
		}

		try {

			HttpClient httpClient = MyHttpClient.getHttpClient();
			HttpResponse httpResponse = null;
			if (mRequestType == REQUEST_TYPE_POST) {
				httpPost.setEntity(new UrlEncodedFormEntity(formparams,
						HTTP.UTF_8));// 发出HTTP request
				httpResponse = httpClient.execute(httpPost);// 取得HTTP response
			} else {
				httpResponse = httpClient.execute(httpGet);// 取得HTTP response
			}

			if (httpResponse.getStatusLine().getStatusCode() == 200) {// 若状态码为200（http协议规定的）,则正常
				String jsonString = this.getJsonString(httpResponse);
				Log.i("jsonString", "jsonString:" + jsonString);
				try {
					if (jsonString != null && !jsonString.equals("")) {
						responseObject = new JSONObject(jsonString);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("HttpTask", "Error Response: "
						+ httpResponse.getStatusLine().toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("HttpTask", "请求异常 ", e);
			return null;
		} finally {
			if (mRequestType == REQUEST_TYPE_POST) {
				httpPost.abort();
			} else {
				httpGet.abort();
			}

		
		}
		return responseObject;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (this.mRequestObject.isShowProgress() && this.mActivity != null) {
			this.mDialog = new ProgressDialog(this.mActivity);
			// String text =
			// mActivity.getResources().getString(R.string.dialog_please_waiting);
			mDialog.setMessage("发送中...");
			mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

				public void onCancel(DialogInterface dialog) {
					HttpTask.this.cancel(true);
				}
			});
			this.mDialog.show();
		}
	}

	@Override
	protected void onPostExecute(JSONObject result) {
		// 网络返回处理
		if (this.mIHttpResponse != null) {
			if (result != null) {
				this.mIHttpResponse.doHttpResponse(result.opt("jsonp"),
						mRequestID);
			}
		}
		// 进度条处理
		if (this.mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		reset();
		// 最终停止Task
		if (this.isCancelled() == false) {
			this.cancel(true);
		}
		super.onPostExecute(result);

	}

	@Override
	protected void onCancelled() {
		if (this.mIHttpResponse != null) {
			this.mIHttpResponse.doHttpCanceled(this.mRequestID);
		}
		super.onCancelled();
	}

	/**
	 * 开始启用
	 * 
	 * @param requestObject
	 */
	@SuppressWarnings("unchecked")
	public HttpTask start(final RequestObject requestObject, int requestID,
			int requestType) {
		if (requestObject == null) {
			return null;
		}
		this.mRequestType = requestType;
		this.mActivity = requestObject.activity;
		this.uriAPI = requestObject.uriAPI;
		this.mRequestObject = requestObject;
		this.mIHttpResponse = (IHttpResponse) mActivity;
		this.mRequestID = requestID;
		this.execute(requestObject.requestHashMap);
		return this;
	}

	public static HttpClient getHttpClient(int timeout) {
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
		HttpConnectionParams.setSoTimeout(httpParams, timeout);
		HttpClient httpClient = new DefaultHttpClient(httpParams);
		return httpClient;
	}

	// 获取返回的jsonString
	private String getJsonString(HttpResponse response) {
		String jsonString = null;
		try {
			if (this.mRequestObject.getEncoding() == null) {// 没有指定编码方式
				jsonString = EntityUtils
						.toString(response.getEntity(), "utf-8");
			} else {
				HttpEntity entity = response.getEntity();
				BufferedHttpEntity buffHttpEntity = new BufferedHttpEntity(
						entity);
				if (this.mRequestObject.getMaxSize() == 0) {// 没有限制大小
					jsonString = byteToString(EntityUtils
							.toByteArray(buffHttpEntity));
				} else {
					if (buffHttpEntity.getContentLength() < this.mRequestObject
							.getMaxSize()) {
						EntityUtils.toByteArray(buffHttpEntity);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.d("HttpTask", ">>>>>>net output : " + jsonString);
		return jsonString;
	}

	// byte转String
	private String byteToString(byte[] data) {
		String body = null;
		try {
			body = new String(data, this.mRequestObject.getEncoding());
		} catch (UnsupportedEncodingException e) {
			Log.e("HttpTask", e.toString());
		}
		return body;
	}

	public void reset() {
		this.mActivity = null;
		// this.mRequestHashMap = null;
		this.mRequestObject = null;
	}

}
